package com.csj.mvvm.utils

import android.os.CountDownTimer
import android.text.Html
import android.widget.TextView
import com.csj.mvvm.App
import com.csj.mvvm.utils.TimeUtil.builder


class CountDownTimerUtil {

    private var timer: CountDownTimer? = null

    companion object {
        @Volatile
        private var util: CountDownTimerUtil? = null

        fun getInstance() = util ?: synchronized(this) {
            util ?: CountDownTimerUtil().also { util = it }
        }
    }

    /**
     * 启动
     *
     * @param view
     * @param nextSendTime
     */
    fun startTimer(view: TextView, nextSendTime: Long) {
        timer = object : CountDownTimer(nextSendTime * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                view.isEnabled = false
                view.text = (millisUntilFinished / 1000).toString() + "秒后重试"
            }

            override fun onFinish() {
                view.isEnabled = true
                view.text = "重新获取"
            }
        }
        (timer as CountDownTimer).start()
    }

    /**
     * 启动
     *
     * @param view
     * @param nextSendTime
     */
    fun startTimerOfHour(view: TextView, nextSendTime: Long) {
        timer = object : CountDownTimer(nextSendTime * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val h = millisUntilFinished / 1000 / 60 / 60 // 时
                val m = millisUntilFinished / 1000 / 60 % 60 // 分
                val s = millisUntilFinished / 1000 % 60 % 60 // 秒
                view.text = ((if (h > 9) h else "0$h")
                    .toString() + ":"
                        + (if (m > 9) m else "0$m")
                        + ":"
                        + if (s > 9) s else "0$s")
            }

            override fun onFinish() {
                view.text = "00:00:00"
            }
        }
        (timer as CountDownTimer).start()
    }

    /**
     * 启动
     *
     * @param view
     */
    fun startTimerOfHour(view: TextView, stamp: String) {
        // 格式化时间戳为 HH:mm:ss
        val remainingTime: String = TimeUtil.getStringTime(stamp, "HH:mm:ss")
        // 获取总秒数
        val nextSendTime = Integer.valueOf(
            remainingTime.split(":".toRegex()).toTypedArray()[0]
        ) * 60 * 60 + Integer.valueOf(
            remainingTime.split(":".toRegex()).toTypedArray()[1]
        ) * 60 + Integer.valueOf(
            remainingTime.split(":".toRegex()).toTypedArray()[2]
        ).toLong()
        // 初始化 CountDowmTimer
        timer = object : CountDownTimer(nextSendTime * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                // 获取当前时间的 时、分、秒
                val h = millisUntilFinished / 1000 / 60 / 60 // 时
                val m = millisUntilFinished / 1000 / 60 % 60 // 分
                val s = millisUntilFinished / 1000 % 60 % 60 // 秒
                // 拼接时分秒、显示到控件上
                view.text = StringBuilder().append(if (h > 9) h else "0$h").append(":")
                    .append(if (m > 9) m else "0$m").append(":")
                    .append(if (s > 9) s else "0$s").toString()
            }

            override fun onFinish() {
                // 结束时显示
                view.text = "00:00:00"
            }
        }
        // 启动
        (timer as CountDownTimer).start()
    }


    /**
     * @param view   展示的控件
     * @param stamp  结束时间
     * @param resStr string 文字资源
     */
    fun startTimerOfHour(view: TextView, stamp: String?, resStr: Int) {
        val currentTimeStamp = System.currentTimeMillis() / 1000
        val diffTimeStamp = java.lang.Long.valueOf(stamp) - currentTimeStamp
        // 初始化 CountDowmTimer
        timer = object : CountDownTimer(diffTimeStamp * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                // 获取当前时间的 时、分、秒
                val h = millisUntilFinished / 1000 / 60 / 60 // 时
                val m = millisUntilFinished / 1000 / 60 % 60 // 分
                val s = millisUntilFinished / 1000 % 60 % 60 // 秒
                // 拼接时分秒、显示到控件上
                val str: String = builder(
                    if (h > 9) h.toString() else "0$h",
                    ":",
                    if (m > 9) m.toString() else "0$m",
                    ":",
                    if (s > 9) s.toString() else "0$s"
                )
                view.text = Html.fromHtml(strFormat(resStr, str))
            }

            override fun onFinish() {
                // 结束时显示
                view.text = Html.fromHtml(strFormat(resStr, "00:00:00"))
            }
        }
        // 启动
        (timer as CountDownTimer).start()
    }

    /**
     * 销毁
     */
    fun stopTimer() {
        timer?.cancel()
    }


    private fun strFormat(strRes: Int, str: String): String? {
        return java.lang.String.format(App.instance.getString(strRes), str)
    }
}